/**
 \* Created with IntelliJ IDEA.
 \* User: 彭诗杰
 \* Date: 2018/8/3 16:07
 \* Description:  污水类state
 \*/
import API from "../../api/api_sewage";
import util from '../../common/util';

const state = {
  // 当前sewageArea
  sewageArea: {
    "code": "jingzhu16888xiaogan16888",
    "name": "京珠孝感服务区",
    "lon": 114.07,
    "lat": 31.01,
    "pollutionType": "水环境污染源",
    "province": "湖北",
    "city": "孝感",
    "county": "孝南区",
    "state": true,
    "faulty": true,
    "sewageId": "jingzhu16888xiaogan16888",
    "airId": null,
    "noiseId": null,
    "solidId": null,
    "type": "monitoring",
    "airRelation": null,
    "noiseRelation": null,
    "sewageRelation": null,
    "solidRelation": null
  },
  // 当前集成商系统，包括factors监测因子以及factor.latest最新数据
  sewageSystem: {
    "systemCode": "jingzhu16888xiaogan16888",
    "name": "当前系统",
    "factorVos": [{
      "id": "8aa7a8dd6b4a7b4b016b4a7b798c0004",
      "code": "pH",
      "name": "pH",
      "maxValue": 14.00,
      "minValue": 0.00,
      "unit": null,
      "sensorID": "w01001",
      "faulty": true,
      "exceeded": true
    }, {
      "id": "8aa7a8dd6b4a7b4b016b4a7b75d80000",
      "code": "cod",
      "name": "COD",
      "maxValue": 150.00,
      "minValue": 0.00,
      "unit": "mg/L",
      "sensorID": "w01018",
      "faulty": true,
      "exceeded": true
    }, {
      "id": "8aa7a8dd6b4a7b4b016b4a7b78b00003",
      "code": "tN",
      "name": "总氮",
      "maxValue": 50.00,
      "minValue": 0.00,
      "unit": "mg/L",
      "sensorID": "w21001",
      "faulty": true,
      "exceeded": true
    }, {
      "id": "8aa7a8dd6b4a7b4b016b4a7b76d60001",
      "code": "nH3N",
      "name": "氨氮",
      "maxValue": 20.00,
      "minValue": 0.00,
      "unit": "mg/L",
      "sensorID": "w21003",
      "faulty": true,
      "exceeded": false
    }, {
      "id": "8aa7a8dd6b4a7b4b016b4a7b77950002",
      "code": "tP",
      "name": "总磷",
      "maxValue": 10.00,
      "minValue": 0.00,
      "unit": "mg/L",
      "sensorID": "w21011",
      "faulty": true,
      "exceeded": true
    }]
  },
  // 当天全部实时数据
  presents: [],
  // 当天分页实时数据
  presentPagingList: [],
  // 历史数据
  sewageHistoryList: [],
  pagination: {
    page: 0,
    limit: 10,
    total: 100,
  },
};

const getters = {
  sewageSystem: state => {
    return state.sewageSystem;
  },
  sewageHistories: state => {
    return state.sewageHistoryList;
  },
  sewagePresents: state => {
    return state.presents;
  },
  sewagePresentsPaging: state => {
    return state.presentPagingList;
  },
};

const actions = {

  /**
   * 从服务器获取单监测指标数据
   *
   * @param commit
   * @param state
   * @param factorParams
   * @returns {Promise<any>}
   */
  getFactorHistoriesNoPagingAct({commit, state}, factorParams) {
    return new Promise((resolve, reject) => {
      API.getFactorHistoriesNoPaging(factorParams).then(factorValues => {
        resolve(factorValues)
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * 从服务器获取当日实时数据，按指标分类commit到presents state
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getSewagePresentAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      if (!params.factors) {
        reject('当前集成商系统factors为空！');
      }
      let allRows = [];
      for (let factor of params.factors) {
        try {
          let factorParams = {
            sewageId: params.sewageId,
            systemCode: params.systemCode,
            factorCode: factor.code,
            dateStart: params.dateStart,
            dateEnd: params.dateEnd
          };
          let singleValues = await API.getFactorHistoriesNoPaging(factorParams);
          let data = singleValues.map(item => item.value);
          let times = singleValues.map(item => item.time);
          allRows.push({factorName: factor.name, data: data, time: times})
        } catch (e) {
          reject(e)
        }
      }
      commit('setSewagePresents', allRows);
      resolve();
    })
  },

  /**
   * 按指标获取后台当日实时数据并组装成el-table格式
   *
   * @param commit
   * @param state
   * @param params
   * @returns {Promise<any>}
   */
  getSewagePresentPagingAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let sewageHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              sewageId: params.sewageId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getFactorHistoryValues(factorParams);
            let formatFactorHistories = factorHistories.factorValueVos;
            total = factorHistories.total;
            formatFactorHistories.forEach(formatFactorHistory => {
              sewageHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(sewageHistories, 'time');
      console.log('groupedByTime', groupedByTime)
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
        //console.log(allRows)
      });

      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };
      commit('setSewagePresentPagingList', allRows);
      resolve(pagination);
    })
  },

  /**
   * 按指标获取后台历史数据并组装成el-table格式，草特么的难写
   * @param commit
   * @param state
   * @param params
   * @returns {Promise}
   */
  getSewageHistoryListAct({commit, state}, params) {
    return new Promise(async (resolve, reject) => {
      let sewageHistories = [];
      let total = 0;
      try {
        if (params.factors) {
          for (let factor of params.factors) {
            let factorParams = {
              sewageId: params.sewageId,
              systemCode: params.systemCode,
              factorCode: factor.code,
              dateStart: params.dateStart,
              dateEnd: params.dateEnd,
              page: params.pagination.page,
              limit: params.pagination.limit
            };
            let factorHistories = await API.getFactorHistoryValues(factorParams);
            let formatFactorHistories = factorHistories.factorValueVos;
            total = factorHistories.total;
            formatFactorHistories.forEach(formatFactorHistory => {
              sewageHistories.push(formatFactorHistory);
            });
          }
        }
      } catch (err) {
        reject(err)
      }
      let groupedByTime = util.groupArray(sewageHistories, 'time');
      //commit('setSewageHistoriesWithRange', groupedByTime);
      console.log(groupedByTime);
      // 将按时间戳分好的数据按factorId进行赋值
      let allRows = [];
      groupedByTime.forEach(groupedTimeItem => {
        let eachRow = [];
        eachRow.time = groupedTimeItem.initial;
        eachRow.data = [];
        params.factors.forEach(factor => {
          groupedTimeItem.list.forEach(item => {
            if (factor.id === item.factorId) {
              let eachRowItem = {
                id: item.id,
                name: factor.code,
                value: item.value,
                outRange: item.outRange
              };
              eachRow.data.push(eachRowItem);
            }
          })
        });
        allRows.push(eachRow);
      });
      let pagination = {
        total: total,
        page: params.pagination.page,
        limit: params.pagination.limit,
      };
      commit('setSewageHistoryList', allRows);
      resolve(pagination);
    });
  },

  /**
   * 从服务器获取当前服务区水质监测集成商系统
   *
   * @param commit
   * @param state
   * @param area
   * @returns {Promise<any>}
   */
  getSewageSystemsAct({commit, state}, area) {
    return new Promise((resolve, reject) => {
      API.getSewageSystems(area.sewageId).then(systems => {
        resolve(systems);
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * 从服务器获取当前集成商系统监测指标
   * @param commit
   * @param state
   * @param params {sewageId:'', systemCode: ''}
   */
  getSystemFactorsAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getSystemFactors(params).then(factPageVo => {
        resolve(factPageVo);
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  /**
   * 从服务器获取监测指标最新值
   * @param commit
   * @param state
   * @param params sewageId:'', systemCode: '', factorCode: ''
   * @returns {Promise}
   */
  getSewageLatestValueAct({commit, state}, params) {
    return new Promise((resolve, reject) => {
      API.getSewageLatestValue(params).then(factorValue => {
        resolve(factorValue)
      }, error => {
        reject(error)
      }).catch(err => {
        reject(err)
      })
    })
  },

  setSewageHistoryList({commit, state}, data) {
    commit('setSewageHistoryList', data)
  },
  setSewagePagination({commit, state}, data) {
    commit('setSewagePagination', data)
  },
  setSewageLatest({commit, state}, data) {
    commit('setSewageLatest', data)
  },
  setSewageAreaAct({commit, state}, area) {
    commit('setSewageArea', area)
  },
  setSewageSystemAct({commit, state}, system) {
    commit('setSewageSystem', system)
  }
};

const mutations = {
  addSewagePresent(state, entity) {
    state.presents.push(entity)
  },
  setSewagePresents(state, entities) {
    state.presents = entities;
  },
  setSewagePresentPagingList(state, entity) {
    state.presentPagingList = entity;
  },
  setSewageHistoryList(state, entity) {
    state.sewageHistoryList = entity;
  },
  setSewagePagination(state, entity) {
    state.pagination = entity
  },
  setSewageLatest(state, entity) {
    state.latest = entity;
  },
  setSewageArea(state, entity) {
    state.sewageArea = entity;
  },
  setSewageSystem(state, entity) {
    state.sewageSystem = entity;
  },
  setSewageSystemFactors(state, entity) {
    state.sewageSystem.factors = entity;
  },
};

export default {
  state,
  getters,
  actions,
  mutations,
}
